package com.atguigu.gmall.cart.service;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.cart.feign.GmallPmsClient;
import com.atguigu.gmall.cart.feign.GmallSmsClient;
import com.atguigu.gmall.cart.feign.GmallWmsClient;
import com.atguigu.gmall.cart.interceptor.LoginInterceptor;
import com.atguigu.gmall.cart.pojo.Cart;
import com.atguigu.gmall.cart.pojo.UserInfo;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.exception.CartException;
import com.atguigu.gmall.pms.entity.SkuAttrValueEntity;
import com.atguigu.gmall.pms.entity.SkuEntity;
import com.atguigu.gmall.sms.vo.ItemSaleVo;
import com.atguigu.gmall.wms.entity.WareSkuEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private GmallPmsClient pmsClient;

    @Autowired
    private GmallSmsClient smsClient;

    @Autowired
    private GmallWmsClient wmsClient;

    @Autowired
    private CartAsyncService asyncService;

    private static final String KEY_PREFIX = "cart:info:";
    private static final String PRICE_PREFIX = "cart:price:";

    public void saveCart(Cart cart){// skuId count
        //1.获取用户的登录信息：登录去userId，未登录取userKey
        String userId = getUserId();

        // 2.Map<UserId/userKey, Map<skuId, cartJson>>  根据外层的key获取内层的map结构
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(KEY_PREFIX + userId);
        // 判断当前用户的购物车是否包含该商品
        String skuId = cart.getSkuId().toString();
        BigDecimal count = cart.getCount();
        if (hashOps.hasKey(skuId)){
            // 包含则更新数量
            String cartJson = hashOps.get(skuId).toString();
            cart = JSON.parseObject(cartJson, Cart.class); // 数据库购物车
            cart.setCount(cart.getCount().add(count)); // 数据库中的购物车的数量 累加 新增的数量
            // 更新到数据库：redis mysql
            // 更新到mysql  TODO：异步改造
            this.asyncService.updateCart(userId, skuId, cart);
        }else{
            // 不包含，则新增记录
            cart.setUserId(userId);
            cart.setCheck(true);
            // 根据skuid查询sku
            ResponseVo<SkuEntity> skuEntityResponseVo = this.pmsClient.querySkuById(cart.getSkuId());
            SkuEntity skuEntity = skuEntityResponseVo.getData();
            if (skuEntity == null) {
                throw new CartException("新增的商品不存在！");
            }
            cart.setTitle(skuEntity.getTitle());
            cart.setPrice(skuEntity.getPrice());
            cart.setDefaultImage(skuEntity.getDefaultImage());

            // 查询营销信息
            ResponseVo<List<ItemSaleVo>> salesResponseVo = this.smsClient.querySalesBySkuId(cart.getSkuId());
            List<ItemSaleVo> itemSaleVos = salesResponseVo.getData();
            cart.setSales(JSON.toJSONString(itemSaleVos));

            // 查询库存信息
            ResponseVo<List<WareSkuEntity>> listResponseVo = this.wmsClient.queryWareSkusBySkuId(cart.getSkuId());
            List<WareSkuEntity> wareSkuEntities = listResponseVo.getData();
            if (!CollectionUtils.isEmpty(wareSkuEntities)){
                cart.setStore(wareSkuEntities.stream().anyMatch(wareSkuEntity -> wareSkuEntity.getStock() - wareSkuEntity.getStockLocked() > 0));
            }

            // 销售属性
            ResponseVo<List<SkuAttrValueEntity>> responseVo = this.pmsClient.querySaleAttrValuesBySkuId(cart.getSkuId());
            List<SkuAttrValueEntity> skuAttrValueEntities = responseVo.getData();
            cart.setSaleAttrs(JSON.toJSONString(skuAttrValueEntities));

            // 加入购物车时，加入实时价格缓存
            this.redisTemplate.opsForValue().set(PRICE_PREFIX + skuId, skuEntity.getPrice().toString());

            // 新增到数据库
            this.asyncService.insertCart(userId, cart);
        }
        hashOps.put(skuId, JSON.toJSONString(cart));
    }

    private String getUserId() {
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        String userId = userInfo.getUserKey(); // 定义一个userId：登陆了userId，未登录就是userKey
        if (userInfo.getUserId() != null){
            userId = userInfo.getUserId().toString();
        }
        return userId;
    }

    public Cart queryCartByUserIdAndSkuId(Long skuId) {
        String userId = this.getUserId();

        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(KEY_PREFIX + userId);
        if (hashOps.hasKey(skuId.toString())){
            String cartJson = hashOps.get(skuId.toString()).toString();
            return JSON.parseObject(cartJson, Cart.class);
        }

        throw new CartException("您的购物车中没有该商品");
    }

    @Async
    public void execute1(){
        try {
            System.out.println("execute1方法开始执行。。。。");
            TimeUnit.SECONDS.sleep(5);
            int i = 1/0;
            System.out.println("execute1方法结束执行=======");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //return AsyncResult.forValue("hello execute1");
    }

    @Async
    public void execute2(){
        try {
            System.out.println("execute2方法开始执行。。。。");
            TimeUnit.SECONDS.sleep(4);
            System.out.println("execute2方法结束执行=======");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //return AsyncResult.forValue("hello execute2");
    }

    public List<Cart> queryCarts() {
        // 1.获取登录状态
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        String userKey = userInfo.getUserKey();

        // 2.以userKey获取未登录购物车 map<skuId, CartJson>
        BoundHashOperations<String, Object, Object> unloginHashOps = this.redisTemplate.boundHashOps(KEY_PREFIX + userKey);
        List<Object> cartJsons = unloginHashOps.values();
        List<Cart> unloginCarts = null;
        if (!CollectionUtils.isEmpty(cartJsons)){
            unloginCarts = cartJsons.stream().map(cartJson -> {
                Cart cart = JSON.parseObject(cartJson.toString(), Cart.class);
                // 查询购物车时，查询实时价格缓存
                cart.setCurrentPrice(new BigDecimal(this.redisTemplate.opsForValue().get(PRICE_PREFIX + cart.getSkuId())));
                return cart;
            }).collect(Collectors.toList());
        }

        // 3.判断登录（userId==null），直接返回未登录购物车即可
        Long userId = userInfo.getUserId();
        if (userId == null){
            return unloginCarts;
        }

        // 4.把未登录的购物车合并到已登录的购物车中
        BoundHashOperations<String, Object, Object> loginHashOps = this.redisTemplate.boundHashOps(KEY_PREFIX + userId);
        if (!CollectionUtils.isEmpty(unloginCarts)){
            unloginCarts.forEach(cart -> { // cart:未登录购物车记录
                String skuId = cart.getSkuId().toString();
                BigDecimal count = cart.getCount(); // 未登录购物车数量
                // 已登录的购物车中已包含该商品，更新数量；否则新增一条记录
                if (loginHashOps.hasKey(skuId)){
                    // 获取已登录购物车中的对应的购物车记录
                    String cartJson = loginHashOps.get(skuId).toString();
                    // 已登录的购物车对象
                    cart = JSON.parseObject(cartJson, Cart.class);
                    cart.setCount(cart.getCount().add(count));

                    // 更新到mysql
                    this.asyncService.updateCart(userId.toString(), skuId, cart);
                } else {
                    cart.setUserId(userId.toString());

                    this.asyncService.insertCart(userId.toString(), cart);
                }
                // 更新到redis
                loginHashOps.put(skuId, JSON.toJSONString(cart));
            });
        }

        // 5.删除未登录的购物车
        this.redisTemplate.delete(KEY_PREFIX + userKey);
        this.asyncService.deleteCartByUserId(userKey);

        //6.返回已登录的购物车
        List<Object> values = loginHashOps.values();
        if (CollectionUtils.isEmpty(values)){
            return null;
        }
        return values.stream().map(cartJson -> {
            Cart cart = JSON.parseObject(cartJson.toString(), Cart.class);
            // 查询购物车时，查询实时价格缓存
            cart.setCurrentPrice(new BigDecimal(this.redisTemplate.opsForValue().get(PRICE_PREFIX + cart.getSkuId())));
            return cart;
        }).collect(Collectors.toList());
    }

    public void updateNum(Cart cart) {
        // 获取登录状态
        String userId = this.getUserId();

        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(KEY_PREFIX + userId);
        if (hashOps.hasKey(cart.getSkuId().toString())){
            BigDecimal count = cart.getCount();
            String cartJson = hashOps.get(cart.getSkuId().toString()).toString();
            cart = JSON.parseObject(cartJson, Cart.class);
            cart.setCount(count);

            hashOps.put(cart.getSkuId().toString(), JSON.toJSONString(cart));
            this.asyncService.updateCart(userId, cart.getSkuId().toString(), cart);
            return;
        }
        throw new CartException("您的购物车中不包含该商品");
    }

    public void deleteCart(Long skuId) {
        String userId = this.getUserId();

        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(KEY_PREFIX + userId);

        hashOps.delete(skuId.toString());
        this.asyncService.deleteCartByUserIdAndSkuId(userId, skuId);
    }

    public List<Cart> queryCheckedCarts(Long userId) {
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(KEY_PREFIX + userId);
        List<Object> cartJsons = hashOps.values();
        if (CollectionUtils.isEmpty(cartJsons)){
            return null;
        }
        return cartJsons.stream().map(cartJson -> JSON.parseObject(cartJson.toString(), Cart.class)).filter(Cart::getCheck).collect(Collectors.toList());
    }
}
